package com.atguigu.common;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

public class TextStream implements Iterable<String>, Closeable {

    private final BufferedReader reader;

    public TextStream(InputStream in) {
        this(in, StandardCharsets.UTF_8);
    }

    public TextStream(InputStream in, Charset charset) {
        reader = new BufferedReader(new InputStreamReader(in, charset));
    }

    @Override
    public Iterator<String> iterator() {
        return new TextStreamIterator();
    }

    @Override
    public void close() throws IOException {
        reader.close();
    }

    private class TextStreamIterator implements Iterator<String> {

        private String nextLine;

        @Override

        public boolean hasNext() {
            try {
                nextLine = reader.readLine();
            } catch (IOException e) {
                nextLine = null;
            }
            return nextLine != null;
        }

        @Override
        public String next() {
            return nextLine;
        }
    }


    @Override
    public void forEach(Consumer<? super String> action) {
        Iterable.super.forEach(action);
    }

    @Override
    public Spliterator<String> spliterator() {
        return Iterable.super.spliterator();
    }
}
